<script setup lang="ts">
  import { ElTree, FormInstance } from 'element-plus'
  import { getCurrentInstance, reactive, ref } from 'vue'
  import { reqRoleDataScope, reqRoleDeptTreeSelect } from '@/api/system/role'

  const dialogVisible = ref()
  const ruleFormRef = ref<FormInstance>()
  const { proxy }: any = getCurrentInstance()
  const roleForm = reactive({
    roleId: '',
    roleName: '',
    roleKey: '',
    dataScope: '',
    roleSort: '0', // 角色顺序
    menuIds: [] /*所管理菜单*/,
    deptIds: [] /*所管理部门*/,
    menuCheckStrictly: true,
    deptCheckStrictly: true,
  })
  const deptExpand = ref(true)
  const deptNodeAll = ref(false)
  // 部门列表
  const deptOptions = ref([])
  const deptRef = ref<InstanceType<typeof ElTree>>()
  const defaultProps = ref({
    value: 'id',
    label: 'label',
    children: 'children',
  })
  const dataScopeOptions = ref([
    {
      value: '1',
      label: '全部数据权限',
    },
    {
      value: '2',
      label: '自定数据权限',
    },
    {
      value: '3',
      label: '本部门数据权限',
    },
    {
      value: '4',
      label: '本部门及以下数据权限',
    },
    {
      value: '5',
      label: '仅本人数据权限',
    },
  ])
  const dataScopeSelectChange = (value: any) => {
    if (value !== '2') {
      deptRef.value.setCheckedKeys([])
    }
  }

  /*获取选中的节点数据*/
  const getDeptAllCheckedKeys = () => {
    roleForm.deptIds = deptRef.value!.getCheckedKeys(false)
  }

  // 提交按钮（数据权限）
  const submitDataScope = async () => {
    if (roleForm.roleId) {
      getDeptAllCheckedKeys()
      await reqRoleDataScope(roleForm).then((response) => {
        proxy.$modal.msgSuccess('修改成功')
        dialogVisible.value = false
      })
    }
  }

  /** 根据角色ID查询部门树结构 */
  const getDeptTree = (roleId) => {
    return reqRoleDeptTreeSelect(roleId).then((response) => {
      deptOptions.value = response.depts
      return response
    })
  }

  // 树权限（展开/折叠）
  const handleCheckedTreeExpand = (value: boolean, type: string) => {
    if (type == 'dept') {
      let treeList = deptOptions.value
      for (let i = 0; i < treeList.length; i++) {
        deptRef.value!.store!.nodesMap[treeList[i].id].expanded = value
      }
    }
  }
  // 树权限（全选/全不选）
  const handleCheckedTreeNodeAll = (value: boolean, type: string) => {
    if (type == 'dept') {
      deptRef.value!.setCheckedNodes(value ? deptOptions.value : ([] as Node[]), false)
    }
  }
  // 树权限（父子联动）
  const handleCheckedTreeConnect = (value: boolean, type: string) => {
    if (type == 'menu') {
      roleForm.menuCheckStrictly = value ? true : false
    } else if (type == 'dept') {
      roleForm.deptCheckStrictly = value ? true : false
    }
  }

  const show = async (item) => {
    console.log(item.roleId)
    Object.keys(item).forEach((key) => {
      roleForm[key] = item[key]
    })

    await getDeptTree(item.roleId).then((req) => {
      roleForm.deptIds = req.checkedKeys
    })

    dialogVisible.value = true
    setTimeout(() => {
      deptRef.value!.setCheckedKeys(roleForm.deptIds, false)
    }, 100)
  }

  const close = () => {
    ruleFormRef.value.resetFields()
    Object.keys(roleForm).forEach((key) => {
      if (key === 'status' || key === 'roleSort') roleForm[key] = '0'
      else if (key === 'menuIds' || key === 'deptIds') roleForm[key] = []
      else if (key === 'menuCheckStrictly' || key === 'deptCheckStrictly') roleForm[key] = true
      else roleForm[key] = ''
    })
  }

  defineExpose({
    show,
  })
</script>

<template>
  <el-drawer v-model="dialogVisible" size="50%" @close="close">
    <template #title>
      <span class="el-drawer__title">分配数据权限</span>
    </template>

    <el-form ref="ruleFormRef" :model="roleForm" label-width="100px">
      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="roleForm.roleName" :disabled="true" />
      </el-form-item>
      <el-form-item label="权限字符" prop="roleKey">
        <el-input v-model="roleForm.roleKey" :disabled="true" />
      </el-form-item>
      <el-form-item label="权限范围">
        <el-select v-model="roleForm.dataScope" @change="dataScopeSelectChange">
          <el-option
            v-for="item in dataScopeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="数据权限" class="el-checkbox-div" v-show="roleForm.dataScope == 2">
        <el-checkbox v-model="deptExpand" @change="handleCheckedTreeExpand($event, 'dept')"
          >展开/折叠</el-checkbox
        >
        <el-checkbox v-model="deptNodeAll" @change="handleCheckedTreeNodeAll($event, 'dept')"
          >全选/全不选</el-checkbox
        >
        <el-checkbox
          v-model="roleForm.deptCheckStrictly"
          @change="handleCheckedTreeConnect($event, 'dept')"
          >父子联动</el-checkbox
        >
        <el-tree
          class="tree-border"
          :data="deptOptions"
          show-checkbox
          default-expand-all
          ref="deptRef"
          node-key="id"
          :check-strictly="!roleForm.deptCheckStrictly"
          empty-text="加载中，请稍候"
          :props="defaultProps"
        ></el-tree>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitDataScope">确定</el-button>
      </span>
    </template>
  </el-drawer>
</template>

<style scoped lang="scss">
  @import '../index';
</style>
